package club.kynb.mall.application.statemachine.order.codition;

import club.kynb.mall.application.context.OrderContext;
import club.kynb.mall.application.model.model.command.CancelOrderCommand;
import club.kynb.mall.order.api.IOrderService;
import club.kynb.mall.order.constant.OrderStatusEnum;
import club.kynb.mall.order.model.dto.OrderDTO;
import lombok.AllArgsConstructor;
import org.pizza.common.web.exception.Errors;
import org.pizza.statemachine.Condition;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author kynb_club@163.com
 * @since 2021/7/9 10:29 上午
 */
@Component
@AllArgsConstructor
public class OrderCancelCondition implements Condition<OrderContext> {
    private final IOrderService iOrderService;

    @Override
    public boolean isSatisfied(OrderContext orderContext) {
        final CancelOrderCommand command = (CancelOrderCommand) orderContext.getCommand();
        final Optional<OrderDTO> optional = iOrderService.getOrderBy(command.getInnerOrderNo());
        if (optional.isPresent()) {
            final OrderDTO orderDTO = optional.get();
            Checker.ifNotThrow(orderDTO.getOrderStatus().equals(OrderStatusEnum.UNPAID.code()), () -> Errors.BIZ.exception("当前订单状态，无法取消订单"));
            return true;
        }
        throw Errors.BIZ.exception("订单编号有误，没有找到对应的订单");
    }

    @Override
    public String name() {
        return Condition.super.name();
    }
}
